import Cookies from 'js-cookie'
import store from '@/store'
import router from '@/router'

/**
 * 权限
 * @param {*} key
 */
export function hasPermission (key) {
  return window.SITE_CONFIG['permissions'].indexOf(key) !== -1 || false
}

/**
 * 获取字典数据列表
 * @param dictType  字典类型
 */
export function getDictDataList (dictType) {
  const type = window.SITE_CONFIG['dictList'][dictType]
  if (type) {
    return type
  } else {
    return []
  }
}
/**
 * 格式化时间
 * @param {*} str
 * @param {*} isFullDate 是否带时分秒
 */
export function fomatDateTime (str, isFullDate = false) {
  let result = ''
  if (str) {
    let date = new Date(str)
    let mon = date.getMonth() + 1
    let day = date.getDate()
    result = date.getFullYear() + '-' + (mon > 10 ? mon : '0' + mon) + '-' + (day > 10 ? day : '0' + day)
    if (isFullDate) {
      let hour = date.getHours()
      let min = date.getMinutes()
      let sec = date.getSeconds()
      result += ' ' + (hour > 10 ? hour : '0' + hour) + ':' + (min > 10 ? min : '0' + min) + ':' + (sec > 10 ? sec : '0' + sec)
    }
    return result
  } else {
    return result
  }
}
/**
 * 获取字典名称
 * @param dictType  字典类型
 * @param dictValue  字典值
 */
export function getDictLabel (dictType, dictValue) {
  if (!window.SITE_CONFIG['dictList']) {
    return dictValue
  }
  const type = window.SITE_CONFIG['dictList'][dictType]
  // .find((element) => (element.dictType === dictType))
  // const type = window.SITE_CONFIG['dictList'].find((element) => (element.dictType === dictType))
  if (type && type.length) {
    const val = type.find((element) => {
      return element.code === dictValue
    })
    if (val) {
      return val.value
    } else {
      return dictValue
    }
  } else {
    return dictValue
  }
}
export function getWrDictLabel (dictType, dictValue) {
  var list = Object.keys(window.SITE_CONFIG['dictList'])
  var name = ''
  for (let i = 0; i < list.length; i++) {
    if (dictType === list[i]) {
      name = dictType + ''
    }
  }
  if (name !== '') {
    const val = window.SITE_CONFIG['dictList'][name].find((element) => (element.code === dictValue + ''))
    if (val) {
      return val.value
    } else {
      return ''
    }
  }
}
/**
 * 清除登录信息
 */
export function clearLoginInfo () {
  store.commit('resetStore')
  Cookies.remove('access_token')
  window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = false
}

/**
 * 获取uuid
 */
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

/**
 * 获取svg图标(id)列表
 */
export function getIconList () {
  var res = []
  document.querySelectorAll('svg symbol').forEach(item => {
    res.push(item.id)
  })
  return res
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'pid') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (!temp[data[k][pid]] || data[k][id] === data[k][pid]) {
      res.push(data[k])
      continue
    }
    if (!temp[data[k][pid]]['children']) {
      temp[data[k][pid]]['children'] = []
    }
    temp[data[k][pid]]['children'].push(data[k])
    data[k]['_level'] = (temp[data[k][pid]]._level || 0) + 1
  }
  return res
}

// 关闭当前窗口
export function closeCurrentTab (data) {
  var tabName = store.state.contentTabsActiveName
  store.state.contentTabs = store.state.contentTabs.filter(item => item.name !== tabName)
  if (store.state.contentTabs.length <= 0) {
    store.state.sidebarMenuActiveName = store.state.contentTabsActiveName = 'home'
    return false
  }
  if (tabName === store.state.contentTabsActiveName) {
    router.push({ name: store.state.contentTabs[store.state.contentTabs.length - 1].name,
      params: { ...store.state.contentTabs[store.state.contentTabs.length - 1].params },
      query: { ...store.state.contentTabs[store.state.contentTabs.length - 1].query }
    })
  }
}
/**
 * 业务最多精确到分，也就是两位小数，最少就是取整，不留小数
 * 现有程序保证2位精度准确
 */
export function moneySwitch (money, precision) { // precision是需要精确的位数，如百分位就是2
  let result = 0
  // 先进行一个千分位的四舍五入，保证3.0999这种情况在保留一位小数的时候能是对的，这一位可以这么做没什么问题
  let moneyTemp = parseFloat(money).toFixed(precision + 1)
  try {
    let intPart = moneyTemp.split('.')[0] // 小数点前的整数
    let pointNum = moneyTemp.split('.')[1] // 取小数点后面的小数
    let precisionNum = pointNum[precision]
    if (precisionNum > 4) { // 五入的情况
      if (precision === 1) {
        pointNum = parseInt(pointNum) + 100 + ''
        if (pointNum.length > 3) { // 说明往整数位进1
          intPart = parseInt(intPart) + 1 + ''
          pointNum = pointNum[1]
        } else {
          pointNum = pointNum[0]
        }
        result = parseFloat(intPart + '.' + pointNum)
      } else if (precision === 2) {
        pointNum = parseInt(pointNum) + 10 + ''
        if (pointNum.length > 3) { // 说明往整数位进1
          intPart = parseInt(intPart) + 1 + ''
          pointNum = pointNum[1] + pointNum[2]
        } else {
          pointNum = pointNum[0] + pointNum[1]
        }
        result = parseFloat(intPart + '.' + pointNum)
      } else if (precision === 3) {
        intPart = parseInt(intPart) + 1 + ''
        pointNum = pointNum[0] + pointNum[1] + pointNum[2]
      }
      result = parseFloat(intPart + '.' + pointNum)
    } else { // 四舍的情况
      if (precision === 1) {
        pointNum = pointNum[0]
      } else if (precision === 2) {
        pointNum = pointNum[0] + pointNum[1]
      } else if (precision === 3) {
        pointNum = pointNum[0] + pointNum[1] + pointNum[2]
      }
      result = parseFloat(intPart + '.' + pointNum)
    }
  } catch (e) {
    return parseFloat(money).toFixed(2) // 如果过程中有出错就tofixed代替为解决
  }
  return result
}
// 新启页面打开
export function openOther (url = '', openType = 0) {
  // 直接copy过来的不知道对不对，测试过了请删除
  let locl = window.location
  // let configUrl = window.location
  // if (configUrl === "")
  let configUrl = ''
  console.log(url, openType, 'openTypeopenTypeopenType')
  let page = window.open('_blank')
  if (openType === 0) {
    configUrl = locl.origin + '/#/'
    if (url && configUrl) {
      // window.open(configUrl + url, false)
      page.location = configUrl + url
    }
  } else if (openType === 1) {
    // 内部网址
    configUrl = window.location
    if (url) {
      page.location = configUrl.origin + '/#/' + url
    }
  } else if (openType === 2) {
    // 全UR了
    if (url) {
      page.location = url
    }
  }
}
